package cn.smbms.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smbms.pojo.Order_detail;
import cn.smbms.pojo.Product;
import cn.smbms.pojo.User;
import cn.smbms.pojo.User_address;
import cn.smbms.service.order_detail.OrderDetailService;
import cn.smbms.service.product.ProductService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.MyMD5;

import com.alibaba.fastjson.JSONArray;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;
	@Resource
	private OrderDetailService orderDetailService;
	@Resource
	private ProductService productService;
	private int number;

	// 注册
	@RequestMapping("/zhu.html")
	public String getZhu() {
		return "zhu";
	}

	// 注sql
	@RequestMapping(value = "/wanc.html", method = RequestMethod.POST)
	public String useradd(@RequestParam String registerkeyword,
			@RequestParam String registermobile, Model model,
			HttpServletRequest request, @RequestParam String registercaptcha) {
		String pwd = MyMD5.getMD5(registerkeyword);
		int i = userService.add(registermobile, pwd);
		if (i > 0) {
			return "wanc";
		}
		return "zhu";
	}

	// 查询电话号码是否注册过
	@RequestMapping(value = "/getphone", method = RequestMethod.POST)
	@ResponseBody
	public Object getPhone(@RequestParam String phone) {
		HashMap<String, String> resultMap = new HashMap<String, String>();
		User user = userService.getUser(phone);
		if (user != null) {
			resultMap.put("res", "true");

		} else {
			resultMap.put("res", "false");
		}
		return JSONArray.toJSONString(resultMap);

	}

	// 注册
	@RequestMapping(value = "/phone.html", method = RequestMethod.POST)
	public String getPhone(@RequestParam String registerkeyword,
			@RequestParam String registermobile, HttpServletRequest request,
			Model model) {
		request.setAttribute("ph", registermobile);

		request.setAttribute("pwd", registerkeyword);
		model.addAttribute("pwd", registerkeyword);
		model.addAttribute("phone", registermobile);
		return "phone";
	}

	/**
	 * 查看个人消费记录
	 */
	@RequestMapping("/sys/getUserOrder")
	public String getUserOrder(Model model, HttpSession session) {
		User user = (User) session.getAttribute(Constants.USER_SESSION);
		List<Order_detail> Order_detailList = orderDetailService
				.getOrder_details(user.getId());
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
		List<Order_detail> list2 = new ArrayList<Order_detail>();
		Date date1 = null;
		Date date2 = null;
		long day = 0;
		try {
			date1 = myFormat.parse(myFormat.format(new Date()));
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		for (Order_detail order_detail : Order_detailList) {

			try {
				date2 = myFormat.parse(order_detail.getOrder().getCreateTime());

			} catch (ParseException e) {
				e.printStackTrace();
			}
			day = (date1.getTime() - date2.getTime()) / 1000 / 60 / 60 / 24;
			if (order_detail.getZhifu() == 1 && day <= 30 && day >= 0) {
				list2.add(order_detail);
			}
		}

		model.addAttribute("user", user);
		model.addAttribute("record", list2);
		return "balance";
	}

	// 删除地址
	@RequestMapping(value = "/sys/deladdres.html")
	public String deladdres(@RequestParam String id) {
		int i = userService.delAddress(Integer.parseInt(id));
		if (i > 0) {
			return "redirect:/user/sys/addres.html";
		} else {
			return "go-address";
		}

	}

	// 设为默认地址 0改成 1
	@RequestMapping(value = "/sys/moaddresi.html")
	public String saveis(@RequestParam String id, HttpSession session) {
		User user = ((User) session.getAttribute(Constants.USER_SESSION));
		int i = userService.saveaddress(Integer.parseInt(id), user.getId());
		if (i > 0) {
			return "redirect:/user/sys/addres.html";
		} else {
			return "go-address";
		}

	}

	// 保存购买地址
	@RequestMapping(value = "/sys/buyadd.html", method = RequestMethod.POST)
	public String buyadd(User_address useraddress, HttpSession session,
			@RequestParam Integer number, @RequestParam String color,
			@RequestParam String size, @RequestParam String proid) {
		if (useraddress.getId() == 0) {
			useraddress.setId(((User) session
					.getAttribute(Constants.USER_SESSION)).getId());
			int i = userService.innerAddress(useraddress);

			try {
				color = new String(color.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i > 0) {
				userService.saveaddress(userService.getmax(), ((User) session
						.getAttribute(Constants.USER_SESSION)).getId());
				return "redirect:/product/sys/buy.html?number=" + number
						+ "&color=" + color + "&size=" + size + "&proid="
						+ proid;
			} else {
				return "go-address";
			}
		} else {
			int i = userService.updateAddress(useraddress);
			if (i > 0) {
				return "redirect:/user/sys/addres.html";
			} else {
				return "go-address";
			}

		}

	}

	// 保存地址
	@RequestMapping(value = "/sys/addresin.html", method = RequestMethod.POST)
	public String inneradd(User_address useraddress, HttpSession session) {
		if (useraddress.getId() == 0) {
			useraddress.setId(((User) session
					.getAttribute(Constants.USER_SESSION)).getId());
			int i = userService.innerAddress(useraddress);
			if (i > 0) {
				return "redirect:/user/sys/addres.html";
			} else {
				return "go-address";
			}
		} else {
			int i = userService.updateAddress(useraddress);
			if (i > 0) {
				return "redirect:/user/sys/addres.html";
			} else {
				return "go-address";
			}

		}

	}

	// 购买添加地址<%=path %>/user/sys/buy-address.html?number=${number
	// }&color=${color }&size=${size }&proid=${product.id }

	// 进入购买添加地址
	@RequestMapping(value = "/sys/buyaddress.html")
	public String gobuyadd(Model model, @RequestParam Integer number,
			@RequestParam String color, @RequestParam String size,
			@RequestParam String proid, HttpSession session) {

		Product product = productService.getProductid(Integer.parseInt(proid));
		float sum = product.getPrice() * number;

		model.addAttribute("sum", sum);

		model.addAttribute("number", number);
		model.addAttribute("product", product);
		model.addAttribute("color", color);
		model.addAttribute("size", size);

		User_address useraddress = new User_address();
		useraddress.setId(0);
		model.addAttribute(useraddress);

		return "buy-address";
	}

	// 进入添加地址界面
	@RequestMapping(value = "/sys/do-address.html")
	public String goAddressc(Model model, @RequestParam String opr) {
		if (opr.equals("add")) {
			User_address useraddress = new User_address();
			useraddress.setId(0);
			model.addAttribute(useraddress);
			return "go-address";
		}

		return "go-address";
	}

	// 根据id 进入我的地址
	@RequestMapping(value = "/sys/go-address/view/{id}")
	public String goAddress(@PathVariable String id, Model model,
			HttpSession session) {
		User_address useraddress = userService.getAddressuserid(Integer
				.parseInt(id));
		model.addAttribute(useraddress);
		return "go-address";
	}

	// 进入我的资料
	@RequestMapping(value = "/sys/view/{id}", method = RequestMethod.GET)
	public String view(@PathVariable String id, Model model) {
		User user = userService.getUserid(id);
		model.addAttribute(user);
		return "datum";
	}

	// 进入我的 修改 name
	@RequestMapping(value = "/sys/namechange.html", method = RequestMethod.GET)
	public String namechange(@RequestParam String username, Model model) {
		User user = new User();
		String name = null;
		try {
			name = new String(username.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user.setUserName(name);
		model.addAttribute(user);

		return "namechange";
	}

	// 进入 sign.html
	@RequestMapping(value = "/sys/sign.html")
	public String sign() {
		return "sign";
	}

	@RequestMapping(value = "/sys/signsave.html", method = RequestMethod.POST)
	public String signsave(@RequestParam String password,
			@RequestParam String newpassword, HttpSession session) {
		if (((User) session.getAttribute(Constants.USER_SESSION)).getPassword()
				.equals(password)) {
			int i = userService
					.updateUser(((User) session
							.getAttribute(Constants.USER_SESSION)).getId(),
							newpassword);
			if (i > 0) {
				session.removeAttribute(Constants.USER_SESSION);
				return "redirect:/user/login.html";
			} else {
				return "sign";
			}

		}
		return "sign";
	}

	// 删除收藏夹商品
	@RequestMapping(value = "/sys/delCollect")
	@ResponseBody
	public Object delCollect(@RequestParam String id, HttpSession session) {
		int userid = ((User) session.getAttribute(Constants.USER_SESSION))
				.getId();
		int ri = userService.delCllect(Integer.parseInt(id), userid);
		HashMap<String, String> resultMap = new HashMap<String, String>();

		if (ri > 0) {
			resultMap.put("res", "true");

			resultMap.put("proid", id);
		} else {
			resultMap.put("res", "false");
		}
		return JSONArray.toJSONString(resultMap);
	}

	// 个人收藏 进入见面/user/sys/mycollect.html/view/${userSession.id}
	@RequestMapping(value = "/sys/mycolect.html")
	public String mycolect(HttpSession session, HttpServletRequest request) {
		int userid = ((User) session.getAttribute(Constants.USER_SESSION))
				.getId();
		List<Product> product = userService.getProduct(userid);
		request.setAttribute("productlist", product);
		return "mycollect";
	}

	// 地址管理进入界面
	@RequestMapping(value = "/sys/addres.html")
	public String addres(HttpSession session, HttpServletRequest request) {
		Integer userid = ((User) session.getAttribute(Constants.USER_SESSION))
				.getId();
		List<User_address> listUser = userService.getAddressid(userid);
		request.setAttribute("addresslist", listUser);
		System.out.println(listUser);

		return "addres";

	}

	// 修改name
	@RequestMapping(value = "/sys/namechange.html", method = RequestMethod.POST)
	public String namechangesave(HttpSession session,
			@RequestParam String userName) {
		User user = new User();
		user.setUserName(userName);
		user.setSex(-1);
		user.setId(((User) session.getAttribute(Constants.USER_SESSION))
				.getId());
		int i = userService.updateName(user);
		if (i > 0) {
			return "redirect:/user/sys/view/" + user.getId() + "";
		}
		return "namechange";
	}

	// 个人中心页面 进入
	@RequestMapping(value = "/sys/self.html")
	public String myMeassage(HttpSession session) {
		User user = userService.getUser(((User) session
				.getAttribute(Constants.USER_SESSION)).getPhone());
		session.setAttribute(Constants.USER_SESSION, user);

		return "self";
	}

	// 登录进入方法
	@RequestMapping(value = "/login.html")
	public String login() {
		return "login";
	}

	// 退出
	@RequestMapping(value = "/delden.html")
	public String delden(HttpSession session) {
		session.removeAttribute(Constants.USER_SESSION);
		return "redirect:/user/login.html";
	}

	// 登录接口
	@RequestMapping(value = "/login.html", method = RequestMethod.POST)
	@ResponseBody
	public Object login(@RequestParam String phone,
			@RequestParam String password, HttpServletRequest request,
			HttpSession session) {

		User user = userService.getUser(phone);
		if (user == null) {

			return "账号不存在";
		}
		String pwd = MyMD5.getMD5(password);
		if (pwd.equals(user.getPassword())) {
			session.setAttribute(Constants.USER_SESSION, user);
			return "/user/sys/self.html";
		} else {

			return "密码错误";
		}

	}

	@RequestMapping(value = "/getphoneapi.html", method = RequestMethod.POST)
	@ResponseBody
	public Object getphoneapi(HttpServletRequest request,
			@RequestParam(value = "phones") String phones) {
		int max = 9999;
		int min = 1000;
		Random random = new Random();
		number = random.nextInt(max) % (max - min + 1) + min;
		String PostData = "";
		try {
			PostData = "account=1291344851&password=zhp20010924&mobile="
					+ phones
					+ "&content="
					+ java.net.URLEncoder.encode("您的订单编码：" + number
							+ "。如需帮助请联系客服。", "utf-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// out.println(PostData);
		String ret = com.dxton.www.Send.SMS(PostData,
				"http://sms.106jiekou.com/utf8/sms.aspx");
		HashMap<String, String> resultMap = new HashMap<String, String>();

		if (ret != "") {
			System.out.println("我进来了");
			resultMap.put("res", "true");
			resultMap.put("resc", number + "");
		} else {
			System.out.println("我没进来");
			resultMap.put("res", "false");
		}
		return JSONArray.toJSONString(resultMap);
	}

	// 点击忘记密码，进入验证修改密码页面。。朱旭光
	@RequestMapping(value = "/newPassword.html")
	public String newPwd() {
		return "/newPassword";
	}

	// 修改密码点击完成进入这里..朱旭光
	@RequestMapping(value = "/modifyPwd.html", method = RequestMethod.POST)
	public String modifyPwd(HttpSession session,
			@RequestParam String newpassword,
			@RequestParam String newpassword2, @RequestParam String yanzheng,
			@RequestParam String phone) {
		User user = userService.getUser(phone);
		if (number != Integer.parseInt(yanzheng)) {
			System.out.println("验证码不对");
			return "验证码错误";
		} else {
			if (newpassword.equals(newpassword2)) {
				String pwd = MyMD5.getMD5(newpassword);
				int result = userService.updateUser(user.getId(), pwd);
				if (result > 0) {
					System.out.println("修改成功");
					return "redirect:/user/login.html";
				}
			} else {
				System.out.println("两次密码输入不一致");
				return "两次密码输入不一致";
			}
			return "";
		}

	}

}
